﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Taobao.Top.Api;
using Taobao.Top.Api.Request;
using System.Net;
using System.IO;
using Taobao.Top.Api.Domain;
using System.Configuration;
using Taobao.Top.Api.Util;
using System.Xml.Serialization;

namespace TaobaoDistrSales.Test
{
    class Program
    {
            
        static void Main(string[] args)
        {
            //bool result = TestFinally(true);
            //Console.WriteLine(result);
            //result = TestFinally(false);
            //Console.WriteLine(result);


            IncrementTradesGetRequest incrementTradesGetRequest = new IncrementTradesGetRequest();
            //incrementTradesGetRequest.

            //TraderatesGetRequest traderatesGetRequest = new TraderatesGetRequest();
            //traderatesGetRequest.PageSize = 20;
            //traderatesGetRequest.Fields = "tid,oid,role,nick,result,created,rated_nick,item_title,item_price,content,reply";
            //traderatesGetRequest.Role = "buyer";
            //traderatesGetRequest.RateType = "get";
            //PageList<TradeRate> firstTradeRates = Client.TraderatesGet(traderatesGetRequest);
            //Console.WriteLine(firstTradeRates.TotalResults);
            //Console.ReadKey();
            //TestEntity();
            FenXiaoGetOrdersRequest request = new FenXiaoGetOrdersRequest();
            request.PurchaseOrderID = 65228739456108;
            request.PageSize = 10;
            //request.Status = Constants.PurchaseOrder_WAIT_SELLER_SEND_GOODS;// "WAIT_SELLER_SEND_GOODS";
            PageList<PurchaseOrder> firstPurchaseOrderList = Client.FenXiaoGetOrders(request);
            FenXiaoGetProductsRequest pRequest = new FenXiaoGetProductsRequest();
            pRequest.PID = "8564082";
            PageList<FenxiaoProduct> products = Client.FenXiaoGetProducts(pRequest);
                            
            int a = 0;
            a++;

            //#region Test API
            //string[] appKeys = new string[] { "12054451", "12053180", "12053054" };
            //string[] appSecrets = new string[] { "8a6f3f523cb3a720e8aa0976d389b7b2", "dc619c1c49cd257a5c841661a5d17e3d", "f373e2795d1c980ddc4c4babf95a294f"};
             
            //try
            //{
            //    TradeFullinfoGetRequest reqt = new TradeFullinfoGetRequest();
            //    reqt.Tid = 54679248481408;
            //    reqt.Fields = "seller_nick, buyer_nick, title, type, created, sid, tid, seller_rate,buyer_flag, buyer_rate, status, payment, adjust_fee, post_fee, total_fee, pay_time, end_time, modified, consign_time, buyer_obtain_point_fee, point_fee, real_point_fee, received_payment, commission_fee, buyer_memo, seller_memo, alipay_no, buyer_message, pic_path, iid, num, price, buyer_alipay_no, receiver_name, receiver_state, receiver_city, receiver_district, receiver_address, receiver_zip, receiver_mobile, receiver_phone, buyer_email,seller_flag, seller_alipay_no, seller_mobile, seller_phone, seller_name, seller_email, available_confirm_fee, has_post_fee, timeout_action_time, snapshot_url, cod_fee, cod_status, shipping_type, trade_memo, is_3D,orders";
            //    Trade trade = Client.TradeFullinfoGet(reqt);

            //    TradesSoldGetRequest req = new TradesSoldGetRequest();
            //    req.PageSize = new int?(10);
            //    req.StartCreated = new DateTime?(DateTime.Parse("1990.01.01"));
            //    req.EndCreated = new DateTime?(DateTime.Now);
            //    req.Fields =  "seller_nick, buyer_nick, title, type, created, sid, tid, seller_rate,buyer_flag, buyer_rate, status, payment, adjust_fee, post_fee, total_fee, pay_time, end_time, modified, consign_time, buyer_obtain_point_fee, point_fee, real_point_fee, received_payment, commission_fee, buyer_memo, seller_memo, alipay_no, buyer_message, pic_path, iid, num, price, buyer_alipay_no, receiver_name, receiver_state, receiver_city, receiver_district, receiver_address, receiver_zip, receiver_mobile, receiver_phone, buyer_email,seller_flag, seller_alipay_no, seller_mobile, seller_phone, seller_name, seller_email, available_confirm_fee, has_post_fee, timeout_action_time, snapshot_url, cod_fee, cod_status, shipping_type, trade_memo, is_3D,orders";
            //    req.Status = "WAIT_SELLER_SEND_GOODS";
            //    req.Type = "fenxiao";
               
            //    PageList<Taobao.Top.Api.Domain.Trade> rsp = Client.TradesSoldGet(req);

            //    //TradeGetRequest tradeGetRequest =new TradeGetRequest();
            //    //tradeGetRequest.Tid = 54604336709849;
            //    //tradeGetRequest.Fields = "seller_nick, buyer_nick, title, type, created, sid, tid, seller_rate,buyer_flag, buyer_rate, status, payment, adjust_fee, post_fee, total_fee, pay_time, end_time, modified, consign_time, buyer_obtain_point_fee, point_fee, real_point_fee, received_payment, commission_fee, buyer_memo, seller_memo, alipay_no, buyer_message, pic_path,  num, price, buyer_alipay_no, receiver_name, receiver_state, receiver_city, receiver_district, receiver_address, receiver_zip, receiver_mobile, receiver_phone, buyer_email,seller_flag, seller_alipay_no, seller_mobile, seller_phone, seller_name, seller_email, available_confirm_fee, has_post_fee, timeout_action_time, snapshot_url, cod_fee, cod_status, shipping_type, trade_memo, is_3D";
            //    //Trade trade = Client.TradeGet(tradeGetRequest);

            //    //UsersGetRequest ur =new UsersGetRequest ();
            //    //ur.Nicks = "仙人球的家园";
            //    //ur.Fields = "user_id,nick,location";
            //    //PageList<Taobao.Top.Api.Domain.User> users = Client.UsersGet(ur);
            //    FenXiaoGetDistributorsRequest requestd = new FenXiaoGetDistributorsRequest();
            //    requestd.Nicks = "超人小店";
            //    PageList<Distributor> allDistributor = Client.FenXiaoGetDistributors(requestd);

            //    FenXiaoGetOrdersRequest request = new FenXiaoGetOrdersRequest();
            //    request.PageSize = 10;// ResourceManager.Current.OptionsConfig.pagesize;
            //    request.StartCreated = DateTime.Now.AddDays(-6);
            //    request.EndCreated = DateTime.Now;
            //    request.PurchaseOrderID = 54679248481408;// 54606051094908;
            //    request.Status = "WAIT_SELLER_SEND_GOODS";
            //    PageList<PurchaseOrder> firstPurchaseOrderList = Client.FenXiaoGetOrders(request);
                 
            //    //FenXiaoGetProductCatsRequest requestcate = new FenXiaoGetProductCatsRequest();
            //    //requestcate.Fields = "total_results,productcats"; 
            //    //PageList<ProductCat> productCats = Client.FenXiaoGetProductCats(requestcate);

            //    //RefundsReceiveGetRequest request = new RefundsReceiveGetRequest();
            //    //request.PageSize = 10;// ResourceManager.Current.OptionsConfig.pagesize;
            //    //request.Fields = "refund_id, tid, title, buyer_nick, seller_nick, total_fee, status, created, refund_fee, oid, good_status, company_name, sid, payment, reason, desc, has_good_return, modified, order_status ";
            //    //PageList<Refund> firstRefunds = Client.RefundsReceiveGet(request);


            //    FenXiaoGetProductsRequest request1 = new FenXiaoGetProductsRequest();
            //    request1.PID = firstPurchaseOrderList.Content[0].SubPurchaseOrders[0].ItemID.ToString();
            //    request1.Fields = "skus,images";
            //    request1.PageSize = 10;// ResourceManager.Current.OptionsConfig.pagesize;
            //    PageList<FenxiaoProduct> products = Client.FenXiaoGetProducts(request1);
            //}
            //catch (Exception e)
            //{
            //}
            //#endregion
        }
        

        #region Fields

        private const string TopUrl = "http://gw.api.taobao.com/router/rest";
        private const string TopKey = "12053041";
        private const string TopSecrets = "ff07ac27681ef9cffa7282c4e052adfb";
        private const bool IsMock = false;
        private static TopXmlRestClient client = null;
        private static TopXmlRestClient Client
        {
            get
            {
                if (client == null)
                {
                    if (IsMock)
                    {
                        client = new TopXmlRestClient("", "", ""); //Mock
                    }
                    else
                    {
                        client = new TopXmlRestClient(TopUrl, TopKey, TopSecrets);
                    }
                }
                return client;
            }
        }
        #endregion

        #region API Test

        private static string getSessionKey(string auth_code)
        {
            try
            {
                HttpWebResponse response = (HttpWebResponse)WebRequest.Create("http://container.open.taobao.com/container?authcode=" + auth_code).GetResponse();
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return "Error";
                }
                Stream dataStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(dataStream);
                string responseFromServer = reader.ReadToEnd();
                string[] sArray = responseFromServer.Split(new char[] { '&' });
                foreach (string i in sArray)
                {
                    if (i.ToString().StartsWith("top_session"))
                    {
                        return i.ToString().Substring(i.ToString().IndexOf("=") + 1);
                    }
                }
                reader.Close();
                dataStream.Close();
                response.Close();
                return responseFromServer;
            }
            catch (WebException e)
            {
                return ("Error:" + e.Status);
            }
            catch (Exception e)
            {
                return ("Error:" + e.Message);
            }
        }

        private static List<PurchaseOrder> GetPurchaseOrders()
        {
            TopContext context = TopUtils.GetTopContext("TOP-109c11fe0b9654268c9b8462dfc48f04b29dPfABqEF9g5YjwwUI5MwdUf39BkSi-END");
            string session = getSessionKey(TopKey);
            
            FenXiaoGetOrdersRequest request = new FenXiaoGetOrdersRequest();
            return Client.FenXiaoGetOrders(request, session).Content;
        }

        private static void Test()
        { 
            string key = "12053041";
            string secrets = "ff07ac27681ef9cffa7282c4e052adfb";
            TopXmlRestClient topClient = new TopXmlRestClient("http://gw.api.taobao.com/router/rest", key, secrets);

            TradesSoldGetRequest req1 = new TradesSoldGetRequest();
            req1.PageSize = 20;
            //不能用创建时间来判断订单
            req1.StartCreated = DateTime.Parse("1990.01.01");//s.Updated;
            req1.EndCreated = DateTime.Now;
            req1.Fields = " title, type, created, sid, tid, received_payment, alipay_no, iid, num, price, shipping_type";
            req1.Status = "WAIT_SELLER_SEND_GOODS";
            PageList<Trade> trades = topClient.TradesSoldGet(req1);
            Trade trade = trades.Content[0];

            //ProductsGetRequest product = new ProductsGetRequest();
            // //topClient.ProductsGet(product);
            TradeFullinfoGetRequest req = new TradeFullinfoGetRequest();
            req.Fields = "seller_nick,end_time, buyer_nick, title, type, created, sid, tid,  status, payment, discount_fee, adjust_fee, post_fee, total_fee, pay_time, buyer_memo, seller_memo, alipay_no, buyer_message,  iid, num, price, buyer_alipay_no, receiver_name, receiver_state, receiver_city, receiver_district, receiver_address, receiver_zip, receiver_mobile, receiver_phone, buyer_email, shipping_type, trade_memo, is_3D ,orders.title, orders.price,orders.oid, orders.num, orders.iid,  orders.status, orders.tid, orders.total_fee, orders.payment, orders.discount_fee, orders.adjust_fee, orders.timeout_action_time,orders.sku_properties_name, orders.item_meal_name, item_memo ";
            req.Tid = new long?(trade.Tid);
            try
            {



                //, getSessionKey("小布叮mp3专卖") 
                Taobao.Top.Api.Domain.Trade rsp = topClient.TradeFullinfoGet(req);


            }
            catch (Exception e)
            {
            }
            finally
            {
            }
        }

        #endregion

        #region Entities Test

        private static void TestEntity()
        {
            TestEntities entites = new TestEntities(ConfigurationManager.ConnectionStrings["TestEntities"].ConnectionString);
            var newUser = new User();
            newUser.Name ="liu";
            newUser.Email = "dd";
            newUser.Company = (from c in entites.Company where c.ID ==1 select c).FirstOrDefault();
            if (newUser.Company == null)
            {
                newUser.Company = new Company();
                newUser.Company.ID = 1;

            }
            else
            {
                newUser.Company.Name = "ddd";
            }
            entites.AddToUser(newUser);
            entites.SaveChanges();

            var user = (from u in entites.User
                        where u.Name == "Ding"
                        select u).FirstOrDefault();
            user.CompanyReference.Load();


        }
        #endregion

        #region XML Test

        private static void TestXML()
        {
            XmlSerializer serializer = new XmlSerializer(typeof(MenuItem));

            StreamReader sReader =new StreamReader ("xmlfile1.xml");
            serializer.Deserialize(sReader);
        }

        #endregion


        public static bool TestFinally(bool value)
        {
            bool result = value;
            try
            {
                return result;
            }
            catch
            {
            }
            finally
            {
                result = false;
            }
            return true;
        }
    }

    [Serializable]
    public class MenuItem
    {
        public MenuItem()
        { }

        [XmlElement("id")]
        public int ID
        { get; set; }

        [XmlElement("name")]
        public string Name
        { get; set; }

        [XmlAttribute("value")]
        public string Value
        { get; set; }
    }
}
